package com.tmall.tmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tmall.tmall.mapper.CategoryMapper;
import com.tmall.tmall.mapper.MainCategoryMapper;
import com.tmall.tmall.pojo.Category;
import com.tmall.tmall.pojo.MainCategory;
import com.tmall.tmall.pojo.PageRt;
import com.tmall.tmall.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private MainCategoryMapper mainCategoryMapper;
    @Override
    public PageRt page(Integer pageNum, Integer pageSize,String name,Integer mid) {
        PageHelper.startPage(pageNum, pageSize);
        List<Category> list = categoryMapper.page(name,mid);
        Map map = new HashMap<Integer,String>();
        for (Category category : list) {
            Integer id=category.getMid();
            if(map.get(id)==null){
                String mName = mainCategoryMapper.getById(id).getName();
                category.setMainName(mName);
                map.put(id,mName);
            }else{
                category.setMainName((String) map.get(id));
            }
        }
        PageInfo<Category> pageInfo = new PageInfo<>(list);
        return new PageRt(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public Category getByName(Category category) {
        return categoryMapper.getByName(category);
    }

    @Override
    public void insert(Category category) {
        categoryMapper.insert(category);
    }

    @Override
    public List<Category> getByMid(Integer mid) {
        return categoryMapper.getByMid(mid);
    }

    @Override
    public void update(Category category) {
        categoryMapper.update(category);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        for (Integer id : ids) {
            Category category = Category.builder().id(id).deleteAt(LocalDateTime.now()).build();
            categoryMapper.update(category);
        }
    }

    @Override
    public List<Category> selectAll() {
        return categoryMapper.selectAll();
    }
}
